//- Copyright (C) 2018-2022 Chatopera Inc, <https://www.chatopera.com>
//- 
//- Licensed under the Apache License, Version 2.0 (the "License");
//- you may not use this file except in compliance with the License.
//- You may obtain a copy of the License at
//- 
//-  http://www.apache.org/licenses/LICENSE-2.0
//- 
//-  Unless required by applicable law or agreed to in writing, software
//- distributed under the License is distributed on an "AS IS" BASIS,
//-  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//- See the License for the specific language governing permissions and
//- limitations under the License.
.uk-layui-form
    form.layui-form.uk-form(action='/admin/user/save.html')
        .layui-form-item
            label.layui-form-label 用户名：
            .layui-input-inline
                input.layui-input(type='text', name='username', required, lay-verify='required_username', placeholder='请输入用户名', autocomplete='off')
            .layui-form-mid.layui-word-aux 用户登录的账号
        .layui-form-item
            label.layui-form-label 姓名：
            .layui-input-inline
                input.layui-input(type='text', name='uname', required, lay-verify='required_name', placeholder='请输入用户姓名', autocomplete='off')
        .layui-form-item
            label.layui-form-label 电子邮件：
            .layui-input-inline
                input.layui-input(type='email', name='email', placeholder='请输入电子邮件地址', autocomplete='off')
        .layui-form-item
            label.layui-form-label 密码：
            .layui-input-inline
                input#password.layui-input(type='password', name='password', required, lay-verify='required|pass', placeholder='请输入登录密码', autocomplete='off')
            .layui-form-mid.layui-word-aux(style='padding-top: 5px;padding-bottom: 0px')
                input#repassword.layui-input(type='password', name='repassword', required, lay-verify='required|repass', placeholder='请再次输入密码', autocomplete='off')
        .layui-form-item
            label.layui-form-label 手机号：
            .layui-input-inline
                input.layui-input(type='mobile', name='mobile', placeholder='请输入手机号码', autocomplete='off')
        .layui-form-item
            .layui-inline
                label.layui-form-label 组织机构：
                .layui-input-inline(style='position: relative;')
                    input#parent(type='hidden', name='parent', value=(currentOrgan ? currentOrgan.id : "0"))
                    input#parentname.layui-input(type='text', name='parentname', required, value=(currentOrgan ? currentOrgan.name : "组织机构"), lay-verify='requiredTwo', autocomplete='off', readonly, onclick='showMenu();')
                    i.layui-icon(style='position: absolute;right: 3px;top: 6px;font-size: 25px;${systemConfig.color!\'color:#0096C4;\'}', onclick='showMenu()') 
                    #menuContent.ukefu-ztree(style='display:none; position: absolute;z-index:10000;width: 218px;')
                        ul#organTree.ztree(style='width:208px;')
        .layui-form-item
            label.layui-form-label 角色：
            .layui-input-inline
                .layui-input-inline(style='width:218px;margin:0px;')
                    select(name='role', required, lay-verify='required')
                        option
                        for r in sysRoles
                            option(value=r.id)= r.name
        .layui-form-item
            label.layui-form-label 管理员：
            .layui-input-inline
                input(type='checkbox', name='admin', lay-skin='switch', lay-filter='admincheckbox', value='1', lay-text='是|否')
            .layui-form-mid.layui-word-aux(style='padding: 0 0; line-height: 20px') 管理员具备访问和修改所有系统资源的权限，同时也设定为多媒体坐席
        .layui-form-item#agentDiv
            label.layui-form-label 多媒体坐席：
            .layui-input-inline
                input(type='checkbox', name='agent', lay-skin='switch', value='1', lay-filter='agent', lay-text='开启|关闭')
        if models.contains("callcenter")
            //<div class="layui-form-item" id="callcenterDiv">
            //  <label class="layui-form-label">呼叫中心坐席：</label>
            //  <div class="layui-input-inline">
            //    <input type="checkbox" name="callcenter" lay-skin="switch"  value="1" lay-filter="callcenter" lay-text="开启|关闭">
              //   </div>
              //   <div class="layui-form-mid layui-word-aux" id="sipAccountDiv">
              //      <input type="text" id="sipAccount" name="sipaccount" lay-verify="sip"  placeholder="请输入SIP地址" autocomplete="off" class="layui-input">
            //  </div>
            //</div>
            #callcenter.layui-form-item
                label.layui-form-label 呼叫中心坐席：
                .layui-input-inline(style="margin-left:0px;")
                    input(type="checkbox", name="callcenter", lay-skin="switch", lay-filter="callcenter", value="1", lay-text="开启|关闭")
            #bindext_tip.layui-form-item
                label.layui-form-label 呼叫中心：
                .layui-input-inline
                    select#callcenterhostid(name="pbxhostid", lay-filter="hostid", lay-verify="callcenterhost")
                        option(value="") 请选择呼叫中心
                #extenttions.layui-form-mid(style="padding-top:5px !important;")
                    select#callcenterExtid(name="extensionid", lay-verify="callcenterext")
                        option(value="") 请选择分机
        .layui-form-button
            .layui-button-block
                button.layui-btn(lay-submit, lay-filter='sys-user-create') 提交
                button.layui-btn(lay-submit, lay-filter='sys-user-create-follow') 提交并创建下一个
                button.layui-btn.layui-btn-original(type='reset') 重置
script.
    layui.use('form', function () {
        var form = layui.form();
        form.render(); //更新全部
        form.verify({
            repass: function (value) {
                if (value != $('#password').val()) {
                    return '两次输入的密码不一致，请确认';
                }
            },
            sip: function (value) {
                if ($("input[name=callcenter]:checked").length > 0 && value === '') {
                    return 'SIP地址不能为空，请确认';
                }
            },
            required_username: function (value) {
                if (value.length > 50) {
                    return "用户名不能超过50字";
                }
            },
            required_name: function (value) {
                if (value.length > 100) {
                    return "用户姓名不能超过100字";
                }
            },
            callcenterhost: function (value) {
                if ($("input[name=callcenter]:checked").length > 0 && value === '') {
                    return '呼叫中心不能为空，请确认';
                }
            },
            callcenterext: function (value) {
                if ($("input[name=callcenter]:checked").length > 0 && value === '') {
                    return '分机不能为空，请确认';
                }
            }
        });

        // 当账号为管理员类型时，强制设定为坐席！
        form.on('switch(admincheckbox)', function (data) {
            if (data.elem.checked) {
                // 坐席的按钮
                if ($('#agentDiv > div > div > em').text() == "关闭") {
                    // 之前未开启
                    document.querySelector('#agentDiv > div > div > i').click();
                }
                // 设置为禁用
                $("#agentDiv > div > input[name=agent]").attr('disabled', 'disabled');
            } else {
                // 取消禁用
                $("#agentDiv > div > input[name=agent]").removeAttr('disabled');
            }
        });

        $('#bindext_tip').hide();

        form.on('switch(callcenter)', function (data) {
            if (data.elem.checked) {
                $('#bindext_tip').show();
                restApiRequest({
                    silent: true,
                    path: 'callcenter',
                    data: {
                        ops: "my-pbxlist"
                    }
                }).then(function (result) {
                    if (result.rc == 0) {
                        $("#callcenterhostid").html('<option value="">请选择呼叫中心</option>');
                        if (result.data.length > 0) {
                            for (var i = 0; i < result.data.length; i++) {
                                $("#callcenterhostid").append('<option value="' + result.data[i].id + '">' + result.data[i].name + '</option>')
                            }
                            ;
                            form.render("select");
                        }
                    }
                }, function (err) {
                    handleRestApiFail(err);
                });
            } else {
                $('#bindext_tip').hide();
            }
        });

        form.on('select(hostid)', function (data) {
            restApiRequest({
                silent: true,
                path: 'callcenter',
                data: {
                    ops: "ext-dd-vacant",
                    id: data.value
                }
            }).then(function (result) {
                if (result.rc == 0) {
                    if (result.data.length > 0) {
                        $("#callcenterExtid").html('<option value="">请选择分机</option>');
                        for (var i = 0; i < result.data.length; i++) {
                            $("#callcenterExtid").append('<option value="' + result.data[i].id + '">' + result.data[i].extension + '</option>')
                        }
                        ;
                        form.render("select");
                    }
                }
            }, function (err) {
                handleRestApiFail(err);
            });
        });

        // 根据“多媒体坐席”显示“呼叫中心坐席”状态
        // form.on('switch(agent)', function(data){
        //     $("input[name=callcenter]").prop("checked", false);
        //     form.render('checkbox','callcenter');
        //     if(data.elem.checked){
        //        $('#callcenterDiv').show();
        //     }else{
        //        $('#callcenterDiv').hide();
        //     }
        //     $('#sipAccount').val("");
        //     $('#sipAccountDiv').hide();
        // });

        // 根据“呼叫中心坐席”状态 显示呼叫地址输入框
        // form.on('switch(callcenter)', function(data){
        //     $('#sipAccount').val("");
        //     if(data.elem.checked){
        //        $('#sipAccountDiv').show();
        //     }else{
        //        $('#sipAccountDiv').hide();
        //     }
        // });

        form.on('submit(sys-user-create)', function (data) {
            data.field['ops'] = 'create';
            restApiRequest({
                silent: true,
                path: 'user',
                data: data.field
            }).then(function (result) {
                if (result.rc == 0) {
                    processUserAddOrUpdateResult(result.data, function () {
                        // close win
                        // 关闭form
                        $("span.layui-layer-setwin > a.layui-layer-close1").click();
                        // 刷新页面
                        document.getElementById("admin").contentWindow.location = '/admin/user/index.html';
                    });
                }
            }, function (err) {
                handleRestApiFail(err);
            });
            return false;
        });

        // 保存成功后，继续留在当前页面，重制并创建下一个
        form.on('submit(sys-user-create-follow)', function (data) {
            data.field['ops'] = 'create';
            restApiRequest({
                silent: true,
                path: 'user',
                data: data.field
            }).then(function (result) {
                if (result.rc == 0) {
                    processUserAddOrUpdateResult(result.data, function () {
                        // 清空部分参数
                        $('input[name="username"]').val("");
                        $('input[name="uname"]').val("");
                        $('input[name="mobile"]').val("");
                        $('input[name="email"]').val("");
                        $('input[name="callcenter"]').attr('checked', false);
                        $('#bindext_tip').hide();
                        $("#callcenterExtid").html('<option value="">请选择分机</option>');
                        form.render('checkbox')
                    });
                }
            }, function (err) {
                handleRestApiFail(err);
            });
            return false;
        })
    });

script(type='text/javascript').
    var setting = {
        data: {simpleData: {enable: true}},
        callback: {onClick: onClick, beforeClick: beforeClick}
    }
    function beforeClick(treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj("organTree")
        nodes = zTree.getSelectedNodes();
        var allow = true, lastnode;
        for (var i = 0, l = nodes.length; i < l; i++) {
            lastnode = nodes[i].type;
            if (nodes[i].organ && (nodes.length >= 1 && (event.ctrlKey || event.shiftKey))) {
                allow = false;
                break;
            }
        }
        if (lastnode != treeNode.type && (event.ctrlKey || event.shiftKey)) {
            allow = false;
        }
        if (allow == false) {
            top.layer.alert("组织机构不能点选多个上级机构，也不能同时选择地区和机构", {icon: 3});
            return false;
        } else {
            return true;
        }
    }
    function onClick(e, treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj("organTree"), nodes = zTree.getSelectedNodes(), v = "", value = "";
        nodes.sort(function compare(a, b) {
            return a.id - b.id;
        });
        for (var i = 0, l = nodes.length; i < l; i++) {
            v += nodes[i].name + ",";
            if (value != "") {
                value = value + ",";
            }
            value = nodes[i].id;
        }
        if (v.length > 0) v = v.substring(0, v.length - 1);
        if (treeNode.type == "area") {
            $("#parentname").attr("value", v);
            $("#parent").attr("value", "0");
            $("#area").attr("value", value);
        } else {
            $("#parentname").attr("value", v);
            $("#parent").attr("value", value);
            $("#area").attr("value", "");
        }
        if (!event.ctrlKey && !event.shiftKey) {
            hideMenu();
        }
    }

    var zNodes = !{pugHelper.toJSON(organList)};
    $.each(zNodes, function (i, o) {
        o.pId = o.parent;
        o.open = true;
        o.organ = true;
        o.type = "organ";
        o.icon = "/images/dept.png"
    })

    $(document).ready(function () {
        var ztree = $.fn.zTree.init($("#organTree"), setting, zNodes);
        if ('#{organData}') {
            var node = ztree.getNodeByParam('id', '#{organData.parent}');//获取id为1的点
            ztree.selectNode(node);//选择点
            if (node) {
                $("#parentname").attr("value", node.name);
            }
            if ('#{organData.area}') {
                var areaList = '#{organData.area}'.split(",")
                areaList.forEach(function (area, index) {
                    var areanode_#{index} = ztree.getNodeByParam('id', area);//获取id为1的点
                    ztree.selectNode(areanode_#{index}, true);//选择点
                });
            }
        }
    })

    function showMenu() {
        $("#menuContent").css({left: "0px", top: "38px"}).show();

        $("body").bind("mousedown", onBodyDown);
    }
    function hideMenu() {
        $("#menuContent").hide();
        $("body").unbind("mousedown", onBodyDown);
    }
    function onBodyDown(event) {
        if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length > 0)) {
            hideMenu();
        }
    }

